package com.bjpowernode.shop.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.shop.base.BaseSearch;
import com.bjpowernode.shop.domain.ProdEs;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/search")
public class SearchController extends BaseSearch {
    /*
    分页查询es中的数据，并排序：关键字查询、排序、分页、高亮
        综合：按照好评率，由高到低
        销量：由高到低
        价格：由低到高
    */

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @GetMapping("/searchProdPage")
    public ResponseEntity<Page<ProdEs>> searchProdPage(Integer current, Integer size, String prodName, Integer sort) {
        // 创建查询条件
        NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();

        // 关键词查询
        query.withQuery(
                // 查询字段，查询关键词
                QueryBuilders.matchQuery("prodName", prodName)
        );

        // 排序查询
        String fieldSort = "";
        switch (sort) {
            case 0:
                fieldSort = "positiveRating"; // 综合：根据好评率倒叙排序
                break;
            case 1:
                fieldSort = "soldNum"; // 销量
                break;
            case 2:
                fieldSort = "price"; // 价格
                break;
        }
        query.withSort(
                SortBuilders.fieldSort(fieldSort).order(
                        sort.equals(2) ? SortOrder.ASC : SortOrder.DESC
                )
        );

        // 分页查询
        query.withPageable(PageRequest.of(current, size));

        // 高亮查询
        query.withHighlightBuilder(
                new HighlightBuilder()
                        .field("prodName").preTags("<i style='color: red'>").postTags("</i>"));

        // 执行查询，获取结果集
        SearchHits<ProdEs> searchHits = elasticsearchRestTemplate.search(query.build(), ProdEs.class);

        // 准备封装结果集
        List<ProdEs> prodEsList = new ArrayList<>();

        // 遍历数据，封装结果集
        searchHits.forEach(
                hit -> {
                    // 获取高亮结果集
                    List<String> highlightList = hit.getHighlightField("prodName");
                    if (!CollectionUtils.isEmpty(highlightList)) {
                        // 封装高亮结果集
                        prodEsList.add(
                                hit.getContent()
                                        .setProdName(highlightList.get(0)));
                    }
                }
        );

        // 封装分页数据
        Page<ProdEs> page = new Page<>(current, size);
        page.setRecords(prodEsList);
        // 分页的记录总数
        page.setTotal(searchHits.getTotalHits());

        return ResponseEntity.ok(page);
    }
}
